package com.lou.springboot.interceptor;

import com.lou.springboot.common.ResultVOUtil;
import com.lou.springboot.entity.Reader;
import com.lou.springboot.enums.ResultEnum;
import com.lou.springboot.service.ReaderService;
import com.lou.springboot.utils.CookieUtils;
import com.lou.springboot.utils.IpUtils;
import com.lou.springboot.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ReaderInterceptor implements HandlerInterceptor {
    @Autowired
    private ReaderService readerService;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception{
        String uri = request.getRequestURI();
        // 判断session中是否存在reader
        if (!uri.startsWith("/admin") && CookieUtils.getCookieValue(request, "reader", true) == null) {
            String addressIp = IpUtils.getIpAddr(request);
//            String address = IpUtils.getIpInfo(addressIp);

            // 根据ip获取用户信息，如果用户第一次访问就创建用户，否则更新用户访问次数
            Reader reader = readerService.getReaderByIp(addressIp);
            if (reader == null) {
                reader = readerService.addReader(addressIp);
            }
            CookieUtils.setCookie(request, response, "reader", JsonUtils.objectToJson(reader), true);
        }
        return true;
    }
}
